﻿using System;
using System.Configuration;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace WWLauncher.Upgrade
{
    public class Downloader
    {
        private readonly HttpClient client;
        private readonly string updateDirect = Path.Combine(Environment.CurrentDirectory, "Upgrade");
        public Downloader()
        {
            client = new HttpClient();
            Url = ConfigurationManager.AppSettings["Url"];
            DownloadDirect = Path.Combine(updateDirect, "下载");
            UnzipDirect = Path.Combine(updateDirect, "解压");
            BackupDirect = Path.Combine(updateDirect, "备份");

            if (!Directory.Exists(DownloadDirect))
                Directory.CreateDirectory(DownloadDirect);
            if (!Directory.Exists(UnzipDirect))
                Directory.CreateDirectory(UnzipDirect);
            if (!Directory.Exists(BackupDirect))
                Directory.CreateDirectory(BackupDirect);
        }
        public string Url { get; set; }
        public string DownloadDirect { get; set; }
        public string UnzipDirect { get; set; }
        public string BackupDirect { get; set; }


        /// <summary>
        /// 查找服务器上比当前版本新的包列表
        /// </summary>
        /// <param name="version">当前版本</param>
        public async Task<RetuenValue> GetServerInfo(string version)
        {
            try
            {
                var resp = await client.GetAsync($"{Url}?version={version}");
                if (!resp.IsSuccessStatusCode)
                    throw new HttpRequestException("查找更新失败", null, resp.StatusCode);

                var res = await resp.Content.ReadAsStringAsync();
                var info = JsonSerializer.Deserialize<RetuenValue>(res.ToString());
                if (info is null)
                    throw new Exception("异常");
                return info;
            }
            catch
            {
                return new RetuenValue();
            }
        }

        /// <summary>
        /// 下载指定版本的包
        /// </summary>
        public async Task DownloadPackage()
        {
            string version = Guid.NewGuid().ToString();
            string packageName = Path.Combine(DownloadDirect, $"{version}.zip");
            var resp = await client.GetAsync($"{Url}/?version=lastest");
            if (!resp.IsSuccessStatusCode)
                throw new HttpRequestException("下载更新失败", null, resp.StatusCode);

            using Stream stream = await resp.Content.ReadAsStreamAsync();
            using FileStream fs = new FileStream(packageName, FileMode.OpenOrCreate, FileAccess.Write);
            await stream.CopyToAsync(fs);

        }
    }
    public class RetuenValue
    {
        public string Information { get; set; }
        public string PackageUrl { get; set; }
        public object PackageVersion { get; internal set; }
    }
}
